package api

import (
	"encoding/json"
	"errors"
	"net/http"
	"strconv"

	"github.com/ammyhaber/seckill/pkg/breaker"
	"github.com/ammyhaber/seckill/pkg/errcode"
	"github.com/ammyhaber/seckill/pkg/utils"
	"github.com/ammyhaber/seckill/service/order/middleware"
	"github.com/ammyhaber/seckill/service/order/model"
	"github.com/ammyhaber/seckill/service/order/service"
)

// OrderAPI 订单API层
type OrderAPI struct {
	orderService *service.OrderService
}

// NewOrderAPI 创建订单API
func NewOrderAPI(orderService *service.OrderService) *OrderAPI {
	return &OrderAPI{orderService: orderService}
}

// CreateOrder 创建订单
func (a *OrderAPI) CreateOrder(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req model.OrderCreateRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.UserID <= 0 || req.ProductID <= 0 || req.Quantity <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 获取订单服务熔断器
	orderBreaker := middleware.GetBreakerManager().GetBreaker("orderCreateService")

	// 使用熔断器包装创建订单操作
	result, err := orderBreaker.ExecuteWithResult("createOrder", func() (interface{}, error) {
		// 创建订单
		return a.orderService.CreateOrder(r.Context(), &req)
	})

	if err != nil {
		if errors.Is(err, breaker.ErrFallback) || errors.Is(err, breaker.ErrCircuitOpen) {
			utils.Fail(w, errcode.ServerError, "订单服务暂时不可用，请稍后再试")
			return
		}
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	orderInfo, ok := result.(*model.OrderInfo)
	if !ok {
		utils.Fail(w, errcode.ServerError, "返回结果类型错误")
		return
	}

	utils.Success(w, orderInfo)
}

// PayOrder 支付订单
func (a *OrderAPI) PayOrder(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req model.OrderPayRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.OrderID <= 0 || req.UserID <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 支付订单
	err := a.orderService.PayOrder(r.Context(), &req)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}

// CancelOrder 取消订单
func (a *OrderAPI) CancelOrder(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req model.OrderCancelRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.OrderID <= 0 || req.UserID <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 取消订单
	err := a.orderService.CancelOrder(r.Context(), &req)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}

// GetOrderDetail 获取订单详情
func (a *OrderAPI) GetOrderDetail(w http.ResponseWriter, r *http.Request) {
	// 获取请求参数
	orderIDStr := r.URL.Query().Get("order_id")
	userIDStr := r.URL.Query().Get("user_id")

	if orderIDStr == "" || userIDStr == "" {
		utils.Fail(w, errcode.InvalidParams, "订单ID和用户ID不能为空")
		return
	}

	orderID, err := strconv.ParseInt(orderIDStr, 10, 64)
	if err != nil {
		utils.Fail(w, errcode.InvalidParams, "订单ID格式错误")
		return
	}

	userID, err := strconv.ParseInt(userIDStr, 10, 64)
	if err != nil {
		utils.Fail(w, errcode.InvalidParams, "用户ID格式错误")
		return
	}

	// 查询订单
	req := &model.OrderQueryRequest{
		OrderID: orderID,
		UserID:  userID,
	}

	orderInfo, err := a.orderService.GetOrderByID(r.Context(), req)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, orderInfo)
}

// GetUserOrders 获取用户订单列表
func (a *OrderAPI) GetUserOrders(w http.ResponseWriter, r *http.Request) {
	// 获取请求参数
	userIDStr := r.URL.Query().Get("user_id")
	statusStr := r.URL.Query().Get("status")

	if userIDStr == "" {
		utils.Fail(w, errcode.InvalidParams, "用户ID不能为空")
		return
	}

	userID, err := strconv.ParseInt(userIDStr, 10, 64)
	if err != nil {
		utils.Fail(w, errcode.InvalidParams, "用户ID格式错误")
		return
	}

	// 解析状态参数
	var status *model.OrderStatus
	if statusStr != "" {
		statusVal, err := strconv.Atoi(statusStr)
		if err != nil {
			utils.Fail(w, errcode.InvalidParams, "状态参数格式错误")
			return
		}
		statusEnum := model.OrderStatus(statusVal)
		status = &statusEnum
	}

	// 查询订单列表
	orders, err := a.orderService.GetOrdersByUserID(r.Context(), userID, status)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, orders)
}
